<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>在售商品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="pageQuery" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" clearable v-model="pageQuery.serialNumber" placeholder="商品编号"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" clearable v-model="pageQuery.goodsName" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="分类名称">
        <el-select v-model="pageQuery.typeId" clearable placeholder="请选择分类名称">
          <el-option :label="item.typeName" :value="item.id" v-for="(item, index) in varityList" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-button type="warning" @click="addShop" style="margin-bottom: 20px">添加商品</el-button>
    <el-table size="small" :data="shopList" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <!-- <el-table-column align="center" type="selection" width="60">
      </el-table-column> -->
      <el-table-column align="center" prop="serialNumber" label="商品编号" width="150">
      </el-table-column>
      <el-table-column sortable align="center" prop="goodsName" label="商品昵称" width="150">
      </el-table-column>
      <el-table-column align="center" prop="coverImg" label="商品封面图片" width="150">
        <template slot-scope="scope" v-if="scope.row.coverImg">
          <el-image
            style="width: 100px"
            :src="scope.row.coverImg"
            fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="describeTxt" label="商品描述" width="150">
      </el-table-column>
      <!-- <el-table-column sortable align="center" prop="originalPrice" label="原价(进货价)" width="120">
      </el-table-column> -->
      <el-table-column sortable align="center" prop="sellPrice" label="售卖价（元）" width="120">
      </el-table-column>
      <el-table-column sortable align="center" prop="inventory" label="商品数量" width="120">
      </el-table-column>
      <!-- <el-table-column sortable align="center" prop="brandsId" label="品牌" width="150">
      </el-table-column>
      <el-table-column sortable align="center" prop="typeId" label="类型" width="150">
      </el-table-column> -->
      <!-- <el-table-column sortable align="center" prop="countryOfOrigin" label="原产地" width="100"> -->
      </el-table-column>
      <el-table-column sortable align="center" prop="shippingAddress" label="发货地" width="100">
      </el-table-column>
      <el-table-column sortable align="center" prop="isSell" label="商品状态" width="150">
        <template slot-scope="scope">
          {{scope.row.isSell ? '已上架' : '已下架'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" @click="changeGood(scope.row)">{{scope.row.isSell ? '下架' : '上架'}}</el-button>
          <el-button size="mini" @click="editShop(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteShop(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageQuery" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="editTitle" :visible.sync="editFormVisible" width="40%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input size="small" v-model="editForm.goodsName" auto-complete="off" placeholder="请输入商品昵称"></el-input>
        </el-form-item>
        <el-form-item label="商品封面图片" prop="coverImg">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-change="handleChange"
            :auto-upload="false"
            :before-upload="beforeAvatarUpload">
            <img v-if="editForm.coverImg" :src="editForm.coverImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="describeTxt">
          <el-input size="small" v-model="editForm.describeTxt" auto-complete="off" placeholder="请输入商品描述"></el-input>
        </el-form-item>
      <el-form-item label="分类名称" prop="typeId">
        <el-select v-model="editForm.typeId" clearable placeholder="请选择分类名称">
          <el-option :label="item.typeName" :value="item.id" v-for="(item, index) in varityList" :key="index"></el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="商品数量" prop="inventory">
          <el-input size="small" v-model="editForm.inventory" auto-complete="off" placeholder="请输入商品数量"></el-input>
        </el-form-item>
        <el-form-item label="售卖价（元）" prop="sellPrice">
          <el-input size="small" v-model="editForm.sellPrice" auto-complete="off" placeholder="请输入售卖价（元）"></el-input>
        </el-form-item>
        <!-- <el-form-item label="原产地" prop="countryOfOrigin">
          <el-input size="small" v-model="editForm.countryOfOrigin" auto-complete="off" placeholder="请输入原产地"></el-input>
        </el-form-item> -->
        <el-form-item label="发货地" prop="shippingAddress">
          <el-input size="small" v-model="editForm.shippingAddress" auto-complete="off" placeholder="请输入发货地"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm(editOrAdd ? 'editForm' : 'addForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import Pagination from '../../components/Pagination'
export default {
  name:'User',
  data() {
    return {
      varityList: [], // 分类列表
      brandList: [], // 品牌列表
      editOrAdd: true, // 编辑 / 新增 => true / false
      shopList: [], //商品列表
      pageQuery: {
        serialNumber: '', // 商品编号
        goodsName: '', // 商品名称
        // brandsId: '', // 品牌名称
        typeId: '', // 分类名称
        isSell: '',
        pageNum: 1,
        pageSize: 10
      },
      loading: false, //是显示加载
      editFormVisible: false, // 编辑框是否弹出
      editTitle: '编辑商品',
      editForm: {
        id: '',
        userId: '',
        brandsId: '',
        typeId: '',
        goodsName: '',
        coverImg: '',
        describeTxt: '',
        // originalPrice: '',
        sellPrice: '',
        // countryOfOrigin: '',
        shippingAddress: '',
        inventory: ''
      },
      // rules表单验证
      rules: {
        goodsName: [
          { required: true, message: '请输入商品昵称', trigger: 'blur' }
        ],
        // originalPrice: [{ required: true, message: '请输入原价', trigger: 'blur' }],
        sellPrice: [{ required: true, validator: (rule, value, callback) => {
      const age= /^[0-9]*$/
      if (!age.test(value)) {
        callback(new Error('价格只能为数字'))
      }else{
        callback()
      }
    }, trigger: 'blur' }],
        // countryOfOrigin: [{ required: true, message: '请输入原产国', trigger: 'blur' }],
        shippingAddress: [{ required: true, message: '请输入发货地', trigger: 'blur' }],
        // brandsId: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        typeId: [{ required: true, message: '请选择分类', trigger: 'change' }]
      },
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  created() {
    this.getShopList(this.pageQuery)
    this.getBrandList()
    this.getVarityList()
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    /**
     * 获取品牌列表
     */
    getBrandList () {
      this.$api.varity.getBrandList().then(res => {
        if (res.code === 200) {
          this.brandList = res.data
        }
      })
    },
    /**
     * 获取分类列表
     */
    getVarityList () {
      this.$api.varity.getVarityList().then(res => {
        if (res.code === 200) {
          this.varityList = res.data
        }
      })
    },
    /**
     * 编辑弹框保存商品修改信息
     */
    submitForm (msg) {
      this.editForm.userId = this.user.id
      if (msg === 'editForm') {
        this.$api.shop.discShop(this.editForm).then(res => {
          if (res.code === 200) {
            this.editFormVisible = false
            this.getShopList(this.pageQuery)
          }
        }).catch(err => this.editFormVisible = false)
      } else {
        delete this.editForm.id
        this.$api.shop.addShop(this.editForm).then(res => {
          if (res.code === 200) {
            this.editFormVisible = false
            this.getShopList(this.pageQuery)
          }
        })
      }
    },
    /**
     * 获取商品列表
     */
    getShopList(pageQuery) {
      this.loading = true
      this.$api.shop.getShopList(pageQuery).then(res => {
        if (res.code === 200) {
          this.shopList = res.data.records
          this.loading = false
        }
      }).catch(err => this.loading = false)
    },
    /**
     * 分页插件事件
     */
    callFather(parm) {
      this.pageQuery.pageNum = parm.currentPage
      this.pageQuery.pageSize = parm.pageSize
      this.getShopList(this.pageQuery)
    },
    /**
     * 关闭编辑、增加弹出框
     */
    closeDialog() {
      this.editFormVisible = false
    },
    /**
     * 对货品上下架
     */
    changeGood (shop) {
      let params = {
        id: shop.id,
        isSell: Number(!shop.isSell)
      }
      this.$api.shop.controlShop(params).then(res => {
        if (res.code === 200) {
          this.getShopList(this.pageQuery)
        }
      })
    },
    /**
     * 编辑商品
     */
    editShop (shop) {
      this.editOrAdd = true
      this.editFormVisible = true
      this.editTitle = "编辑商品"
      this.editForm.id = shop.id
      this.editForm.brandsId = shop.brandsId
      this.editForm.typeId = shop.typeId
      this.editForm.goodsName = shop.goodsName
      this.editForm.describeTxt = shop.describeTxt
      this.editForm.coverImg = shop.coverImg
      // this.editForm.originalPrice = shop.originalPrice
      this.editForm.sellPrice = shop.sellPrice
      // this.editForm.countryOfOrigin = shop.countryOfOrigin
      this.editForm.shippingAddress = shop.shippingAddress
    },
    /**
     * 搜索商品列表
     */
    search () {
      this.getShopList(this.pageQuery)
    },
    /**
     * 增加商品
     */
    addShop () {
      this.editOrAdd = false
      this.editFormVisible = true
      this.editTitle = "添加商品"
      this.editForm.brandsId = ''
      this.editForm.typeId = ''
      this.editForm.goodsName = ''
      this.editForm.coverImg = ''
      this.editForm.describeTxt = ''
      // this.editForm.originalPrice = ''
      this.editForm.sellPrice = ''
      // this.editForm.countryOfOrigin = ''
      this.editForm.shippingAddress = ''
    },
    /**
     * 删除商品
     */
    deleteShop (index, shop) {
      this.$api.shop.deleteShop({id:shop.id}).then(res => {
        if (res.code === 200) {
          this.getShopList(this.pageQuery)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.editForm.coverImg = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传商品封面图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    /****
     * 上传图片 起步函数
     */
    handleChange (file) {
      this.submitUpload(file)
    },
    /***
     * 上传图片 上传函数
     */
    submitUpload (file) {
        let formData = new FormData() //  用FormData存放上传文件
        formData.append('file', file.raw, file.raw.name)
        this.$api.auth.uploadImage(formData).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '上传成功!'
            })
            this.editForm.coverImg = res.data
          }
        })
    },
  }
}
</script>

<style>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.el-form-item{
  margin-bottom: 15px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

 
 